package com.java.ratelimter.listener;

import com.google.common.util.concurrent.RateLimiter;
import com.java.ratelimter.RateLimterApplication;
import com.java.ratelimter.aop.RateLimter;
import com.java.ratelimter.constant.LimterConstant;
import com.java.ratelimter.util.ClassUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author : i_smchen
 * create at:  2019/4/4  下午6:49
 * @description: 负责在spring容器加载完成之后启动queue线程
 */
@Component
@Slf4j
public class SpringFinishedListener implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        //扫描注解
        //获取当前的包名
        String packageName = RateLimterApplication.class.getPackage().getName();
        List<Class<?>> classList = ClassUtil.getClasses(packageName);
        //扫描当前包及其子包下的所有类
        classList.forEach(clazz -> {
            //获得所有的方法
            Method[] methods = clazz.getMethods();
            if (methods != null) {
                //获得注解使用了@RateLimter的方法
                for (Method method : methods) {
                    //判断该方法是否使用了@MyTest注解
                    boolean annotationPresent = method.isAnnotationPresent(RateLimter.class);
                    if (annotationPresent) {
                        //该方法使用RateLimter注解了
                        RateLimter rateLimter = clazz.getAnnotation(RateLimter.class);
                        LimterConstant.LIMITER_MAP.put(rateLimter.rateKey(), RateLimiter.create(rateLimter.rate()));
                    }
                }
            }
        });
    }
}
